import React, { useState, useEffect } from 'react';
import { Form, Input, InputNumber, DatePicker, Select, Button, Upload, message, Space, Switch, TimePicker, Checkbox } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import { request } from 'umi';
import moment from 'moment';

const { TextArea } = Input;
const { Option } = Select;
const { RangePicker: TimeRangePicker } = TimePicker;

// 上传图片
const uploadImage = async (file) => {
  const formData = new FormData();
  formData.append('file', file);
  return request('/api/v1/upload', {
    method: 'POST',
    data: formData,
  });
};

const ActivityFormContent = ({ initialValues, onCancel, loading }) => {
  const form = Form.useFormInstance();
  const [storeList, setStoreList] = useState([]);
  const [venueList, setVenueList] = useState([]);
  const [imageUrl, setImageUrl] = useState('');
  const [fileList, setFileList] = useState([]);
  const selectedStoreIds = Form.useWatch('applicable_stores', form);

  // 获取门店列表
  const fetchStoreList = async () => {
    try {
      const res = await request('/api/v1/store', { method: 'GET' });
      if (res.success) {
        setStoreList(res.data.list);
      }
    } catch (error) {
      message.error('获取门店列表失败');
    }
  };

  // 获取场地列表
  const fetchVenueList = async (storeIds) => {
    if (!storeIds || storeIds.length === 0) {
      setVenueList([]);
      return;
    }
    try {
      const requests = storeIds.map(storeId => request(`/api/v1/venue?store_id=${storeId}`, { method: 'GET' }));
      const responses = await Promise.all(requests);
      const newVenueList = responses.reduce((acc, res) => {
        if (res.success && res.data.list) {
          return acc.concat(res.data.list);
        }
        return acc;
      }, []);
      setVenueList(newVenueList);
    } catch (error) {
      message.error('获取场地列表失败');
    }
  };

  useEffect(() => {
    fetchStoreList();
    if (initialValues) {
      if (initialValues.image) {
        setImageUrl(initialValues.image);
        setFileList([{
          uid: '-1',
          name: 'image.png',
          status: 'done',
          url: initialValues.image,
        }]);
      }
      if (initialValues.applicable_stores && initialValues.applicable_stores.length > 0) {
        fetchVenueList(initialValues.applicable_stores);
      }
    } else {
      // 如果没有初始值，重置状态
      setImageUrl('');
      setFileList([]);
      setVenueList([]);
    }
  }, [initialValues]);

  useEffect(() => {
    if (selectedStoreIds) {
      fetchVenueList(selectedStoreIds);
    } else {
      setVenueList([]);
    }
  }, [selectedStoreIds]);

  // 处理门店选择变化，清空已选场地
  const handleStoreChange = (values) => {
    const oldValues = form.getFieldValue('applicable_stores') || [];
    if (values.length < oldValues.length) {
        form.setFieldsValue({ applicable_venues: [] });
    }
  };

  // 处理图片上传
  const handleUploadChange = async (info) => {
    if (info.file.status === 'uploading') {
      return;
    }
    if (info.file.status === 'done') {
      setImageUrl(info.file.response.data.url);
      form.setFieldsValue({ image: info.file.response.data.url });
      message.success('上传成功');
    } else if (info.file.status === 'error') {
      message.error('上传失败');
    }
  };

  // 自定义上传方法
  const customUpload = async ({ file, onSuccess, onError }) => {
    try {
      const res = await uploadImage(file);
      if (res.success) {
        onSuccess(res, file);
      } else {
        onError(new Error('上传失败'));
      }
    } catch (error) {
      onError(error);
    }
  };

  return (
    <>
      <Form.Item
        name="name"
        label="活动名称"
        rules={[{ required: true, message: '请输入活动名称' }]}
      >
        <Input placeholder="请输入活动名称" maxLength={100} />
      </Form.Item>

      <Form.Item
        name="image"
        label="活动图片"
        rules={[{ required: false, message: '请上传活动图片' }]}
      >
        <Upload
          name="file"
          listType="picture-card"
          showUploadList={false}
          customRequest={customUpload}
          onChange={handleUploadChange}
          fileList={fileList}
        >
          {imageUrl ? (
            <img src={imageUrl} alt="活动图片" style={{ width: '100%' }} />
          ) : (
            <div>
              <UploadOutlined />
              <div style={{ marginTop: 8 }}>上传图片</div>
            </div>
          )}
        </Upload>
      </Form.Item>

      <Form.Item
        name="description"
        label="活动描述"
        rules={[{ required: true, message: '请输入活动描述' }]}
      >
        <TextArea rows={4} placeholder="请输入活动描述" maxLength={500} />
      </Form.Item>



      <Form.Item label="价格设置" style={{ marginBottom: 0 }}>
        <Space>
          <Form.Item
            name="original_price"
            rules={[{ required: true, message: '请输入原价' }]}
            style={{ display: 'inline-block', marginBottom: 0 }}
          >
            <InputNumber
              min={0}
              precision={2}
              placeholder="原价"
              addonBefore="原价"
              addonAfter="元"
              style={{ width: 200 }}
            />
          </Form.Item>

          <Form.Item
            name="group_price"
            rules={[{ required: true, message: '请输入团购价' }]}
            style={{ display: 'inline-block', marginBottom: 0 }}
          >
            <InputNumber
              min={0}
              precision={2}
              placeholder="团购价"
              addonBefore="团购价"
              addonAfter="元"
              style={{ width: 200 }}
            />
          </Form.Item>
        </Space>
      </Form.Item>

      <Form.Item label="活动时间" style={{ marginBottom: 0 }}>
        <Space>
          <Form.Item
            name="start_time"
            rules={[{ required: true, message: '请选择开始时间' }]}
            style={{ display: 'inline-block', marginBottom: 0 }}
          >
            <DatePicker
              showTime
              format="YYYY-MM-DD HH:mm:ss"
              placeholder="开始时间"
              style={{ width: 200 }}
            />
          </Form.Item>

          <Form.Item
            name="end_time"
            rules={[{ required: true, message: '请选择结束时间' }]}
            style={{ display: 'inline-block', marginBottom: 0 }}
          >
            <DatePicker
              showTime
              format="YYYY-MM-DD HH:mm:ss"
              placeholder="结束时间"
              style={{ width: 200 }}
            />
          </Form.Item>
        </Space>
      </Form.Item>

      <Form.Item label="参团设置" style={{ marginBottom: 0 }}>
        <Space>
          <Form.Item
            name="min_members"
            rules={[{ required: true, message: '请输入最少参团人数' }]}
            style={{ display: 'inline-block', marginBottom: 0 }}
          >
            <InputNumber
              min={2}
              placeholder="最少参团人数"
              addonBefore="最少"
              addonAfter="人"
              style={{ width: 180 }}
            />
          </Form.Item>

          <Form.Item
            name="max_members"
            rules={[{ required: false }]}
            style={{ display: 'inline-block', marginBottom: 0 }}
          >
            <InputNumber
              min={0}
              placeholder="最大参团人数(0表示不限)"
              addonBefore="最多"
              addonAfter="人"
              style={{ width: 220 }}
            />
          </Form.Item>

          <Form.Item
            name="limit_per_member"
            rules={[{ required: true, message: '请输入每人限购数量' }]}
            style={{ display: 'inline-block', marginBottom: 0 }}
          >
            <InputNumber
              min={1}
              placeholder="每人限购数量"
              addonBefore="每人限购"
              addonAfter="份"
              style={{ width: 200 }}
            />
          </Form.Item>
        </Space>
      </Form.Item>

      <Form.Item
        name="status"
        label="活动状态"
        rules={[{ required: true, message: '请选择活动状态' }]}
      >
        <Select placeholder="请选择活动状态">
          <Option value={1}>启用</Option>
          <Option value={0}>禁用</Option>
        </Select>
        </Form.Item>

        <Form.Item
          name="support_balance"
          label="支持余额支付"
          valuePropName="checked"
        >
          <Switch />
        </Form.Item>

      <Form.Item
        name="deductible_hours"
        label="可抵扣时长（小时）"
        rules={[{ required: true, message: '请输入可抵扣时长' }]}
      >
        <InputNumber min={0} precision={2} placeholder="请输入可抵扣的小时数" style={{ width: '100%' }} />
      </Form.Item>

      <Form.Item
        name="applicable_stores"
        label="可用门店"
        rules={[{ required: false, message: '请选择可用门店' }]}
      >
        <Select
          mode="multiple"
          placeholder="请选择可用门店"
          onChange={handleStoreChange}
          options={storeList.map((store) => ({ label: store.name, value: store.id }))}
        />
      </Form.Item>

      <Form.Item
        name="applicable_venues"
        label="可用场地"
        rules={[{ required: false, message: '请选择可用场地' }]}
      >
        <Select
          mode="multiple"
          placeholder="请选择可用场地"
          options={venueList.map((venue) => ({ label: venue.name, value: venue.id }))}
        />
      </Form.Item>



      <Form.Item
        name="available_weekdays"
        label="可用星期"
      >
        <Checkbox.Group>
          <Checkbox value={1}>周一</Checkbox>
          <Checkbox value={2}>周二</Checkbox>
          <Checkbox value={3}>周三</Checkbox>
          <Checkbox value={4}>周四</Checkbox>
          <Checkbox value={5}>周五</Checkbox>
          <Checkbox value={6}>周六</Checkbox>
          <Checkbox value={0}>周日</Checkbox>
        </Checkbox.Group>
      </Form.Item>

      <Form.List name="available_times">
        {(fields, { add, remove }) => (
          <>
            {fields.map(({ key, name, ...restField }) => (
              <Space key={key} style={{ display: 'flex', marginBottom: 8 }} align="baseline">
                <Form.Item
                  {...restField}
                  name={[name, 'time']}
                  rules={[{ required: true, message: '请选择时间范围' }]}
                >
                  <TimeRangePicker format="HH:mm" />
                </Form.Item>
                <Button onClick={() => remove(name)}>删除</Button>
              </Space>
            ))}
            <Form.Item>
              <Button type="dashed" onClick={() => add()} block>
                添加时间段
              </Button>
            </Form.Item>
          </>
        )}
      </Form.List>

      <Form.Item
        name="sort_order"
        label="排序值"
        rules={[{ required: true, message: '请输入排序值' }]}
      >
        <InputNumber min={0} placeholder="数值越小越靠前" style={{ width: 200 }} />
      </Form.Item>

      <Form.Item>
        <Space>
          <Button type="primary" htmlType="submit" loading={loading}>
            保存
          </Button>
          <Button onClick={onCancel}>取消</Button>
        </Space>
      </Form.Item>
    </>
  );
};

const ActivityForm = ({ form, initialValues, onFinish, onCancel, loading }) => {
  useEffect(() => {
    if (initialValues) {
      form.setFieldsValue({
        ...initialValues,
        start_time: moment(initialValues.start_time * 1000),
        end_time: moment(initialValues.end_time * 1000),
        available_times: initialValues.available_times ? initialValues.available_times.map(t => ({
          time: [moment(t.start_time, 'HH:mm'), moment(t.end_time, 'HH:mm')]
        })) : [],
      });
    } else {
      form.resetFields();
      form.setFieldsValue({
        status: 1,
        min_members: 2,
        max_members: 0,
        limit_per_member: 1,
        sort_order: 0,
        support_balance: false,
        start_time: moment(),
        end_time: moment().add(7, 'days'),
        available_weekdays: [],
        available_times: [],
      });
    }
  }, [initialValues, form]);

  return (
    <Form
      form={form}
      layout="vertical"
      onFinish={(values) => {
        const data = {
          ...values,
          start_time: values.start_time.unix(),
          end_time: values.end_time.unix(),
          available_times: values.available_times ? values.available_times.map(t => ({
            start_time: t.time[0].format('HH:mm'),
            end_time: t.time[1].format('HH:mm'),
          })) : [],
        };
        onFinish(data);
      }}
    >
      <ActivityFormContent initialValues={initialValues} onCancel={onCancel} loading={loading} />
    </Form>
  );
};

export default ActivityForm;